<template>
	<view class="exam-detail-container">
		<!-- 头部信息 -->
		<view class="exam-header">
			<button class="btn-back" @click="goBack">
				<image src="/image/fanhui.png" mode="aspectFit"></image>
			</button>
			<view class="header-info">
				<view class="exam-title">{{ examInfo.title || '加载中...' }}</view>
				<view class="exam-meta">
					<text>总分: {{ examInfo.totalScore }}分</text>
					<text class="divider">|</text>
					<text>时长: {{ examInfo.duration }}分钟</text>
				</view>
			</view>
			<view class="timer" v-if="isExaming && remainingTime">
				<image src="/image/shijian.png" mode="aspectFit"></image>
				<text>{{ remainingTime }}</text>
			</view>
		</view>
		
	<!-- 题目内容 -->
	<view class="question-content">
		<!-- 加载中 -->
		<view v-if="loading" class="loading-state">
			<text>加载中...</text>
		</view>
		
		<!-- 加载错误 -->
		<view v-else-if="loadError" class="error-state">
			<image src="/image/dingdan.png" mode="aspectFit"></image>
			<text class="error-title">加载失败</text>
			<text class="error-message">{{ loadError }}</text>
			<button class="retry-btn" @click="getExamQuestions">重新加载</button>
			<button class="back-btn" @click="goBack">返回</button>
		</view>
		
		<!-- 无数据 -->
		<view v-else-if="!currentQuestion" class="empty-state">
			<text>暂无题目</text>
		</view>
		
		<!-- 题目卡片 -->
		<view v-else class="question-card">
			<view class="question-header">
				<view class="question-type">{{ currentQuestion.type }}</view>
				<view class="question-score">{{ currentQuestion.score }}分</view>
			</view>
			
			<view class="question-title">
				<text class="number">{{ currentIndex + 1 }}. </text>
				<!-- 富文本题目（包含HTML） -->
				<view v-if="currentQuestion.questionType >= 5" class="html-content" v-html="currentQuestion.title"></view>
				<!-- 普通文本题目 -->
				<text v-else>{{ currentQuestion.title }}</text>
			</view>
			
			<!-- 单选题 -->
			<view class="options" v-if="currentQuestion.type === '单选题'">
				<view class="option-item" 
					v-for="(option, index) in currentQuestion.options" 
					:key="index"
					:class="{ selected: currentQuestion.answer === option.key, readonly: currentQuestion.isReadOnly }"
					@click="!currentQuestion.isReadOnly && selectOption(option.key)">
					<image class="radio" 
						:src="currentQuestion.answer === option.key ? '/image/danxuankuang-xuanzhong.png' : '/image/danxuankuang-moren.png'" 
						mode="aspectFit">
					</image>
					<text class="option-key">{{ option.key }}.</text>
					<text class="option-text">{{ option.text }}</text>
				</view>
			</view>
			
			<!-- 多选题 -->
			<view class="options" v-if="currentQuestion.type === '多选题'">
				<view class="option-item" 
					v-for="(option, index) in currentQuestion.options" 
					:key="index"
					:class="{ selected: currentQuestion.answer.includes(option.key), readonly: currentQuestion.isReadOnly }"
					@click="!currentQuestion.isReadOnly && toggleOption(option.key)">
					<image class="checkbox" 
						:src="currentQuestion.answer.includes(option.key) ? '/image/fuxuankuang-xuanzhong.png' : '/image/fuxuankuang-moren.png'" 
						mode="aspectFit">
					</image>
					<text class="option-key">{{ option.key }}.</text>
					<text class="option-text">{{ option.text }}</text>
				</view>
			</view>
			
			<!-- 判断题 -->
			<view class="judge-options" v-if="currentQuestion.type === '判断题'">
				<view class="judge-item" 
					:class="{ selected: currentQuestion.answer === true, readonly: currentQuestion.isReadOnly }"
					@click="!currentQuestion.isReadOnly && selectJudge(true)">
					<image 
						:src="currentQuestion.answer === true ? '/image/danxuankuang-xuanzhong.png' : '/image/danxuankuang-moren.png'" 
						mode="aspectFit">
					</image>
					<text>正确</text>
				</view>
				<view class="judge-item" 
					:class="{ selected: currentQuestion.answer === false, readonly: currentQuestion.isReadOnly }"
					@click="!currentQuestion.isReadOnly && selectJudge(false)">
					<image 
						:src="currentQuestion.answer === false ? '/image/danxuankuang-xuanzhong.png' : '/image/danxuankuang-moren.png'" 
						mode="aspectFit">
					</image>
					<text>错误</text>
				</view>
			</view>
			
			<!-- 简答题 -->
			<view class="answer-input" v-if="currentQuestion.type === '简答题'">
				<textarea 
					v-model="currentQuestion.answer" 
					placeholder="请输入答案..."
					:readonly="currentQuestion.isReadOnly"
					maxlength="500">
				</textarea>
				<view class="word-count">{{ currentQuestion.answer ? currentQuestion.answer.length : 0 }}/500</view>
			</view>
			
			<!-- 图文题 -->
			<view class="answer-input" v-if="currentQuestion.type === '图文题'">
				<textarea 
					v-model="currentQuestion.answer" 
					placeholder="请输入答案..."
					:readonly="currentQuestion.isReadOnly"
					maxlength="500">
				</textarea>
				<view class="word-count">{{ currentQuestion.answer ? currentQuestion.answer.length : 0 }}/500</view>
			</view>
			
			<!-- 批改模式：评分输入框 -->
			<view class="score-input" v-if="mode === 'correct' && (currentQuestion.type === '简答题' || currentQuestion.type === '图文题' || currentQuestion.type === '填空题')">
				<view class="score-label">评分:</view>
				<input 
					type="digit" 
					v-model.number="currentQuestion.judgeScore" 
					placeholder="请输入得分"
					:maxlength="5">
				</input>
				<view class="score-total">/ {{ currentQuestion.score }}分</view>
			</view>
		</view>			<!-- 题目导航 -->
			<view class="question-nav">
				<view class="nav-title">答题卡</view>
				<view class="nav-grid">
					<view class="nav-item" 
						v-for="(item, index) in questionList" 
						:key="index"
						:class="{ 
							current: currentIndex === index,
							answered: item.answered 
						}"
						@click="goToQuestion(index)">
						{{ index + 1 }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="footer-actions" v-if="currentQuestion">
			<!-- 查看模式：只显示导航按钮 -->
			<view v-if="mode === 'view'">
				<button class="btn btn-prev" @click="prevQuestion" :disabled="currentIndex === 0">
					上一题
				</button>
				<button class="btn btn-next" v-if="currentIndex < questionList.length - 1" @click="nextQuestion">
					下一题
				</button>
				<button class="btn btn-back" v-else @click="goBack">
					返回
				</button>
			</view>
			
			<!-- 批改模式：显示导航和提交批改按钮 -->
			<view v-else-if="mode === 'correct'">
				<button class="btn btn-prev" @click="prevQuestion" :disabled="currentIndex === 0">
					上一题
				</button>
				<button class="btn btn-next" v-if="currentIndex < questionList.length - 1" @click="nextQuestion">
					下一题
				</button>
				<button class="btn btn-submit" v-else @click="submitCorrection">
					提交批改
				</button>
			</view>
			
			<!-- 新做模式：显示完整功能 -->
			<view v-else>
				<button class="btn btn-prev" @click="prevQuestion" :disabled="currentIndex === 0">
					上一题
				</button>
				<button class="btn btn-collect" @click="toggleCollect">
					<image :src="currentQuestion.collected ? '/image/shoucang.png' : '/image/shoucang.png'" mode="aspectFit"></image>
					{{ currentQuestion.collected ? '已收藏' : '收藏' }}
				</button>
				<button class="btn btn-next" v-if="currentIndex < questionList.length - 1" @click="nextQuestion">
					下一题
				</button>
				<button class="btn btn-submit" v-else @click="submitExam">
					提交试卷
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import { api } from '@/http.js'

export default {
	data() {
		return {
			paperId: '',
			recordId: '',
			source: 'list',  // 来源页面：'list'、'record'、'paper'
			mode: 'exam',  // 'exam' 新做试卷, 'view' 查看答卷, 'correct' 批改试卷
			examInfo: {
				title: '',
				totalScore: 0,
				duration: 0
			},
			isExaming: true,
			remainingTime: '00:00:00',
			currentIndex: 0,
			questionList: [],
			loading: false,
			loadError: ''  // 添加错误状态
		}
	},
	computed: {
		currentQuestion() {
			if (this.questionList && this.questionList.length > 0 && this.currentIndex < this.questionList.length) {
				return this.questionList[this.currentIndex];
			}
			return null;
		}
	},
	onLoad(options) {
		console.log('=== detail.vue onLoad ===');
		console.log('接收到的参数:', options);
		
		// 保存来源信息，用于返回时跳转到正确的页面
		this.source = options.source || 'list';
		
		// 判断是查看答卷还是新做试卷
		if (options.recordId) {
			// 查看已提交的答卷
			this.mode = options.mode || 'view';
			this.recordId = options.recordId;
			console.log('答卷ID:', this.recordId);
			console.log('模式:', this.mode);
			this.getExamAnswer();
		} else if (options.id || options.paperId) {
			// 新做试卷
			this.mode = 'exam';
			this.paperId = options.id || options.paperId;
			console.log('试卷ID:', this.paperId);
			this.getExamQuestions();
		} else {
			console.error('未接收到试卷ID或答卷ID');
			uni.showToast({
				title: '缺少参数',
				icon: 'none'
			});
		}
	},
	onShow() {
		// 检查登录状态
		const token = uni.getStorageSync('token');
		if (!token && !this.paperId) {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
	},
	methods: {
		goBack() {
			// 尝试获取当前页面栈
			const pages = getCurrentPages();
			console.log('当前页面栈深度:', pages.length);
			
			// 如果页面栈深度大于1，说明有上一页，可以返回
			if (pages.length > 1) {
				uni.navigateBack({
					delta: 1
				});
			} else {
				// 如果没有上一页（刷新导致栈被清空），跳转到对应的tab页
				// 根据来源参数决定跳转目标
				if (this.source === 'record') {
					uni.switchTab({
						url: '/pages/record/record'
					});
				} else if (this.source === 'paper') {
					uni.switchTab({
						url: '/pages/paper/paper'
					});
				} else {
					// 默认返回列表
					uni.switchTab({
						url: '/pages/exam/list'
					});
				}
			}
		},
		async getExamAnswer() {
			// 获取已提交的答卷详情
			console.log('========== 开始加载答卷 ==========');
			if (!this.recordId) {
				console.error('ERROR: recordId 为空');
				return;
			}
			
			this.loading = true;
			this.loadError = '';
			console.log('答卷ID:', this.recordId);
			
			try {
				console.log('步骤1: 调用 api.getExamPaperDetail()');
				const res = await api.getExamPaperDetail(this.recordId);
				
				console.log('========== API 响应信息 ==========');
				console.log('响应 code:', res?.code);
				console.log('响应 message:', res?.message);
				console.log('完整响应结构:', JSON.stringify(res?.response).substring(0, 500));
				
				if (res?.code === 1 && res?.response) {
					console.log('步骤2: 响应成功，开始加载答卷数据');
					
					// 关键修复：API 返回的是 {paper: {...}, answer: {...}} 结构
					const { paper, answer } = res.response;
					
					console.log('paper 对象的顶级字段:', Object.keys(paper || {}));
					console.log('answer 对象的顶级字段:', Object.keys(answer || {}));
					console.log('paper 基本信息:', {
						id: paper?.id,
						name: paper?.name,
						score: paper?.score,
						titleItems长度: paper?.titleItems?.length
					});
					
					// 诊断：检查 answer 中的答案数据
					if (answer) {
						console.log('answer 数据诊断:', {
							answerList存在: !!answer.answerList,
							list存在: !!answer.list,
							answerListLength: answer.answerList?.length,
							listLength: answer.list?.length
						});
						
						// 打印前3个答案用于诊断
						if (answer.answerList && answer.answerList.length > 0) {
							console.log('answerList 样本 (前3个):', JSON.stringify(answer.answerList.slice(0, 3), null, 2));
						} else if (answer.list && answer.list.length > 0) {
							console.log('list 样本 (前3个):', JSON.stringify(answer.list.slice(0, 3), null, 2));
						}
					}
					
					if (!paper) {
						console.error('ERROR: paper 对象不存在');
						this.loadError = '试卷数据缺失，无法加载';
						return;
					}
					
					// 设置试卷基本信息
					this.examInfo = {
						title: paper.name || '未命名试卷',
						totalScore: paper.score || 100,
						duration: paper.suggestTime || 120
					};
					
					// 建立题目 ID 到答案的映射表
					const answerMap = {};
					// API 返回的实际是 answerItems 字段
					const answerList = answer.answerItems || answer.answerList || answer.list || [];
					if (answer && answerList && answerList.length > 0) {
						answerList.forEach(item => {
							answerMap[item.questionId] = item;
						});
						
						// 诊断：打印答案项的完整信息
						console.log('========== 答案项诊断 ==========');
						answerList.slice(0, 2).forEach((item, idx) => {
							console.log(`第${idx + 1}个答案项:`, {
								id: item.id,
								questionId: item.questionId,
								score: item.score,
								contentArray: item.contentArray,
								content: item.content
							});
						});
					}
					
					console.log('答案映射表:', Object.keys(answerMap).length, '个答案');
					if (Object.keys(answerMap).length === 0) {
						console.warn('⚠️ 警告：没有找到任何答案数据！');
						console.log('完整的 answer 对象:', JSON.stringify(answer, null, 2));
					}
					
					// 解析题目
					const questionList = [];
					
					if (paper.titleItems && paper.titleItems.length > 0) {
						paper.titleItems.forEach((titleItem, titleIdx) => {
							console.log(`\n大题${titleIdx + 1}: ${titleItem.name}`);
							console.log(`  - questionItems 长度: ${titleItem.questionItems?.length}`);
							
							if (titleItem.questionItems && titleItem.questionItems.length > 0) {
								titleItem.questionItems.forEach((q, qIdx) => {
									console.log(`    小题${qIdx + 1}:`);
									console.log(`      - id: ${q.id}`);
									console.log(`      - type: ${q.questionType}`);
									console.log(`      - title: ${q.title?.substring(0, 30)}`);
									console.log(`      - items 长度: ${q.items?.length}`);
									
									const options = (q.items || []).map((item, idx) => ({
										key: item.prefix || String.fromCharCode(65 + idx),
										text: item.content || `选项${idx + 1}`
									}));
									
									// 从答案映射表中查找该题的答案
									let userAnswer = '';
									const answerItem = answerMap[q.id];
									
									if (answerItem) {
										console.log(`      - 用户答案: ${JSON.stringify(answerItem.contentArray || answerItem.content)}`);
										
										const answerContent = answerItem.contentArray || [answerItem.content];
										
										if (q.questionType === 2) {
											// 多选题：从 contentArray 转为数组
											userAnswer = Array.isArray(answerContent) ? answerContent : [answerContent];
										} else if (q.questionType === 3) {
											// 判断题：将 'true'/'false' 字符串转为布尔值
											const firstAnswer = Array.isArray(answerContent) ? answerContent[0] : answerContent;
											userAnswer = firstAnswer === 'true' || firstAnswer === true;
										} else {
											// 其他题型：取第一个元素（或直接用 content）
											userAnswer = Array.isArray(answerContent) ? answerContent[0] : answerContent || '';
										}
									} else {
											console.log(`      - 未找到答案`);
										// 初始化空答案
										if (q.questionType === 2) {
											userAnswer = [];
										} else if (q.questionType === 3) {
											userAnswer = null;
										} else {
											userAnswer = '';
										}
									}
									
									questionList.push({
										id: q.id,
										answerId: answerItem?.id, // 保存答题记录ID，用于批改提交
										titleId: (titleIdx + 1),
										itemOrder: (qIdx + 1),
										type: this.getQuestionType(q.questionType),
										score: parseFloat(q.score) || 0,
										title: q.title || '无标题',
										questionType: q.questionType,
										options: options,
										answer: userAnswer,
										answered: !!answerItem,  // 有答案就标记为已回答
										collected: false,
										isReadOnly: this.mode !== 'correct',  // 批改模式时可以修改评分
										judgeScore: answerItem?.score ? parseFloat(answerItem.score) : 0, // 初始化评分，用于批改模式
										correctAnswer: q.correct // 保存正确答案用于批改参考
									});
								});
							}
						});
					} else {
						console.warn('警告: titleItems 为空或不存在');
						this.loadError = '试卷中没有题目内容';
					}
					
					this.questionList = questionList;
					console.log('\n步骤3: 答卷解析完成');
					console.log('总题目数:', this.questionList.length);
					console.log('有答案的题数:', this.questionList.filter(q => q.answered).length);
					
					if (this.questionList.length > 0) {
						console.log('第一题详细信息:', {
							id: this.questionList[0].id,
							answerId: this.questionList[0].answerId,
							type: this.questionList[0].type,
							score: this.questionList[0].score,
							judgeScore: this.questionList[0].judgeScore,
							answer: this.questionList[0].answer
						});
						console.log('所有题目的 answerId:', this.questionList.map(q => ({
							questionId: q.id,
							answerId: q.answerId,
							type: q.type
						})));
					} else {
						this.loadError = '试卷中没有题目';
					}
					
					// 关闭计时器（查看答卷时不需要计时）
					this.isExaming = false;
				} else {
					console.error('ERROR: 响应失败或数据为空');
					this.loadError = res?.message || '获取答卷失败，请稍后重试';
					uni.showToast({
						title: this.loadError,
						icon: 'none'
					});
				}
			} catch (err) {
				console.error('EXCEPTION: 获取答卷异常:', err);
				this.loadError = '网络错误：获取答卷失败，请检查网络连接后重试';
				uni.showToast({
					title: '获取答卷失败，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				console.log('========== 加载答卷结束 ==========\n');
			}
		},
		async getExamQuestions() {
			console.log('========== 开始加载试卷 ==========');
			if (!this.paperId) {
				console.error('ERROR: paperId 为空');
				return;
			}
			
			this.loading = true;
			this.loadError = '';  // 清除之前的错误
			console.log('试卷ID:', this.paperId);
			
			try {
				console.log('步骤1: 调用 api.selectPaper()');
				const res = await api.selectPaper(this.paperId);
				
				console.log('========== API 响应信息 ==========');
				console.log('步骤2: 收到API响应');
				console.log('响应 code:', res?.code);
				console.log('响应 message:', res?.message);
				console.log('响应 response 类型:', typeof res?.response);
				console.log('响应 response 存在:', !!res?.response);
				
				if (res?.response) {
					console.log('响应 response 内容:', JSON.stringify(res.response).substring(0, 500));
				}
				
				// 检查 code 是否为 500 或其他错误
				if (res?.code === 500) {
					console.error('ERROR: 服务器返回 500 错误');
					console.log('诊断信息: 试卷ID为 ' + this.paperId + ' 的试卷无法从后端加载');
					console.log('可能原因: 1.试卷数据损坏 2.试卷被删除 3.后端有bug');
					this.loadError = '服务器错误：该试卷暂时无法加载，请稍后重试或选择其他试卷';
					uni.showToast({
						title: res?.message || '服务器错误',
						icon: 'none'
					});
				} else if (res?.code === 1 && res?.response) {
					console.log('步骤3: 响应成功，开始解析数据');
					const paper = res.response;
					
					console.log('试卷字段检查:');
					console.log('  - paper.name:', paper.name);
					console.log('  - paper.score:', paper.score);
					console.log('  - paper.suggestTime:', paper.suggestTime);
					console.log('  - paper.titleItems 存在:', !!paper.titleItems);
					console.log('  - paper.titleItems 长度:', paper.titleItems?.length);
					
					this.examInfo = {
						title: paper.name || '未命名试卷',
						totalScore: paper.score || 100,
						duration: paper.suggestTime || 120
					};
					
					console.log('试卷信息已设置:', this.examInfo);
					
					// 解析所有题目
					let questionList = [];
					
					if (paper.titleItems && paper.titleItems.length > 0) {
						console.log('步骤4: 开始解析 titleItems，共', paper.titleItems.length, '个标题');
						
						paper.titleItems.forEach((titleItem, titleIdx) => {
							console.log(`\n大题${titleIdx + 1}: ${titleItem.name}`);
							console.log('  questionItems 长度:', titleItem.questionItems?.length);
							
							if (titleItem.questionItems && titleItem.questionItems.length > 0) {
								titleItem.questionItems.forEach((q, qIdx) => {
									console.log(`    小题${qIdx + 1}:`);
									console.log(`      - id: ${q.id}`);
									console.log(`      - type: ${q.questionType}`);
									console.log(`      - title: ${q.title?.substring(0, 30)}`);
									console.log(`      - items 长度: ${q.items?.length}`);
									
									const options = (q.items || []).map((item, idx) => ({
										key: item.prefix || String.fromCharCode(65 + idx),
										text: item.content || `选项${idx + 1}`
									}));
									
									console.log(`      - 解析的选项: ${JSON.stringify(options)}`);
									
									// 根据题目类型初始化答案
									let initialAnswer = '';
									if (q.questionType === 2) {
										// 多选题：数组
										initialAnswer = [];
									} else if (q.questionType === 3) {
										// 判断题：布尔值
										initialAnswer = null;
									} else {
										// 其他题型（单选、简答、图文等）：字符串
										initialAnswer = '';
									}
									
									questionList.push({
										id: q.id,
										titleId: (titleIdx + 1),
										itemOrder: (qIdx + 1),
										type: this.getQuestionType(q.questionType),
										score: parseFloat(q.score) || 0,
										title: q.title || '无标题',
										questionType: q.questionType,
										options: options,
										answer: initialAnswer,
										answered: false,
										collected: false
									});
								});
							}
						});
					} else {
						console.warn('警告: titleItems 为空或不存在');
						this.loadError = '试卷中没有题目内容';
					}
					
					this.questionList = questionList;
					console.log('\n步骤5: 题目解析完成');
					console.log('总题目数:', this.questionList.length);
					
					if (this.questionList.length > 0) {
						console.log('第一题:', this.questionList[0]);
						// 启动计时器
						this.startTimer();
					} else {
						this.loadError = '试卷中没有题目';
					}
				} else {
					console.error('ERROR: 响应失败或数据为空');
					console.log('完整响应:', JSON.stringify(res));
					this.loadError = res?.message || '获取试卷失败，请稍后重试';
					uni.showToast({
						title: this.loadError,
						icon: 'none'
					});
				}
			} catch (err) {
				console.error('EXCEPTION: 获取试卷异常:', err);
				this.loadError = '网络错误：获取试卷失败，请检查网络连接后重试';
				uni.showToast({
					title: '获取试卷失败，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				console.log('========== 加载试卷结束 ==========\n');
			}
		},
		getQuestionType(type) {
			const typeMap = {
				'1': '单选题',
				'2': '多选题',
				'3': '判断题',
				'4': '简答题',
				'5': '图文题',
				1: '单选题',
				2: '多选题',
				3: '判断题',
				4: '简答题',
				5: '图文题'
			};
			return typeMap[type] || '未知题型';
		},
		selectOption(key) {
			this.currentQuestion.answer = key;
			this.currentQuestion.answered = true;
		},
		toggleOption(key) {
			const answer = this.currentQuestion.answer;
			const index = answer.indexOf(key);
			if (index > -1) {
				answer.splice(index, 1);
			} else {
				answer.push(key);
			}
			this.currentQuestion.answered = answer.length > 0;
		},
		selectJudge(value) {
			this.currentQuestion.answer = value;
			this.currentQuestion.answered = true;
		},
		toggleCollect() {
			this.currentQuestion.collected = !this.currentQuestion.collected;
		},
		prevQuestion() {
			if (this.currentIndex > 0) {
				this.currentIndex--;
			}
		},
		nextQuestion() {
			if (this.currentIndex < this.questionList.length - 1) {
				this.currentIndex++;
			}
		},
		goToQuestion(index) {
			this.currentIndex = index;
		},
		async submitExam() {
			uni.showModal({
				title: '提示',
				content: '确定要提交试卷吗?',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 构建提交数据格式（新格式）
							const answerItems = [];
							
							console.log('=== 开始提交试卷 ===');
							console.log('试卷ID:', this.paperId);
							console.log('总题数:', this.questionList.length);
							
							this.questionList.forEach((q, idx) => {
								let content = null;
								let contentArray = [];
								
								if (typeof q.answer === 'string') {
									// 单选题、简答题、图文题
									content = q.answer || '';
									contentArray = [q.answer || ''];
									console.log(`题目${idx + 1} (${q.id}):`, q.answer || '(未作答)', '类型:', q.type, 'contentArray:', JSON.stringify(contentArray));
								} else if (Array.isArray(q.answer)) {
									// 多选题
									content = q.answer.join(',') || '';
									contentArray = q.answer || [];
									console.log(`题目${idx + 1} (${q.id}):`, q.answer.join(',') || '(未作答)', '类型:', q.type, 'contentArray:', JSON.stringify(contentArray));
								} else if (typeof q.answer === 'boolean') {
									// 判断题
									content = q.answer ? 'true' : 'false';
									contentArray = [q.answer ? 'true' : 'false'];
									console.log(`题目${idx + 1} (${q.id}):`, q.answer, '类型:', q.type, 'contentArray:', JSON.stringify(contentArray));
								} else if (q.answer === null) {
									// 未作答
									contentArray = [];
									console.log(`题目${idx + 1} (${q.id}): (未作答)`, '类型:', q.type, 'contentArray:', JSON.stringify(contentArray));
								}
								
								answerItems.push({
									questionId: q.id,
									content: content,
									contentArray: contentArray,
									completed: !!q.answered,
									itemOrder: q.itemOrder
								});
							});
							
							const submitData = {
								doTime: 1,  // 临时设置为1秒
								id: this.paperId,
								questionId: null,
								answerItems: answerItems
							};
							
							console.log('完整提交数据:', JSON.stringify(submitData, null, 2));
							console.log('answerItems 样本 (前3个):', JSON.stringify(answerItems.slice(0, 3), null, 2));
							
							const submitRes = await api.submitExamAnswer(submitData);
							console.log('提交响应 code:', submitRes?.code);
							console.log('提交响应 message:', submitRes?.message);
							console.log('提交响应 response:', JSON.stringify(submitRes?.response).substring(0, 500));
							
							if (submitRes && submitRes.code === 1) {  // 文档中成功标志是 code === 1
								// 打印完整的响应用于诊断
								console.log('完整提交响应:', JSON.stringify(submitRes, null, 2));
								
								uni.showToast({
									title: '提交成功',
									icon: 'success'
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1,
										fail: () => {
											// 返回失败时，跳转到首页
											uni.switchTab({
												url: '/pages/index/list'
											});
										}
									});
								}, 1500);
							} else {
								uni.showToast({
									title: submitRes?.message || '提交失败',
									icon: 'none'
								});
							}
						} catch (err) {
							console.error('提交试卷错误:', err);
							uni.showToast({
								title: '提交失败，请稍后重试',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		async submitCorrection() {
			// 批改试卷提交
			uni.showModal({
				title: '提示',
				content: '确定要提交批改结果吗?',
				success: async (res) => {
					if (res.confirm) {
						try {
							console.log('=== 开始提交批改 ===');
							
							// 计算总得分和构建提交数据
							let totalScore = 0;
							const answerItems = [];
							
							this.questionList.forEach((q, idx) => {
								let score = 0;
								
								// 对于客观题（单选、多选、判断），根据答案自动判分
								if (q.type === '单选题' || q.type === '多选题') {
									if (Array.isArray(q.answer) && Array.isArray(q.correctAnswer)) {
										// 多选题
										const answerStr = q.answer.sort().join(',');
										const correctStr = q.correctAnswer.sort().join(',');
										score = answerStr === correctStr ? q.score : 0;
									} else if (!Array.isArray(q.answer) && !Array.isArray(q.correctAnswer)) {
										// 单选题
										score = q.answer === q.correctAnswer ? q.score : 0;
									}
								} else if (q.type === '判断题') {
									score = q.answer === q.correctAnswer ? q.score : 0;
								} else {
									// 主观题（填空、简答、图文题），使用教师评分
									score = q.judgeScore || 0;
								}
								
								totalScore += score;
								
								// 构建 content 和 contentArray
								let content = null;
								let contentArray = [];
								
								if (q.type === '填空题' && Array.isArray(q.answer)) {
									content = null;
									contentArray = q.answer;
								} else if (typeof q.answer === 'string') {
									content = q.answer || null;
									contentArray = [q.answer || ''];
								} else if (Array.isArray(q.answer)) {
									content = q.answer.join(',') || null;
									contentArray = q.answer || [];
								} else if (typeof q.answer === 'boolean') {
									content = q.answer ? 'true' : 'false';
									contentArray = [q.answer ? 'true' : 'false'];
								} else if (q.answer === null) {
									content = null;
									contentArray = [];
								}
								
								console.log(`题目${idx + 1} (${q.id}):`, {
									score: score,
									judgeScore: q.judgeScore,
									type: q.type,
									answer: q.answer,
									correctAnswer: q.correctAnswer
								});
								
								answerItems.push({
									id: q.answerId || q.id, // 答题记录ID
									questionId: q.id,
									doRight: null,  // 根据接口文档，这里应该是 null
									content: content,
									itemOrder: q.itemOrder,
									contentArray: contentArray,
									score: score.toString(),
									questionScore: q.score.toString()
								});
							});
							
							// 计算耗时（如果有的话）
							const doTime = this.examInfo.doTime || 1;
							
							const submitData = {
								id: this.recordId, // 答卷ID
								doTime: doTime,
								score: totalScore.toString(),
								answerItems: answerItems
							};
							
							console.log('批改提交数据:', JSON.stringify(submitData, null, 2));
							console.log('answerItems 详细信息:');
							answerItems.forEach((item, idx) => {
								console.log(`  第${idx + 1}题:`, {
									id: item.id,
									questionId: item.questionId,
									score: item.score,
									questionScore: item.questionScore,
									doRight: item.doRight,
									contentArrayLength: item.contentArray.length,
									content: item.content
								});
							});
							
							const submitRes = await api.judgeExamPaper(submitData);
							console.log('批改响应 code:', submitRes?.code);
							console.log('批改响应 message:', submitRes?.message);
							console.log('完整批改响应:', JSON.stringify(submitRes, null, 2));
							
							if (submitRes && submitRes.code === 1) {
								uni.showToast({
									title: '批改成功',
									icon: 'success'
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1,
										fail: () => {
											// 返回失败时，跳转到考试记录页
											uni.switchTab({
												url: '/pages/record/record'
											});
										}
									});
								}, 1500);
							} else {
								uni.showToast({
									title: submitRes?.message || '批改提交失败',
									icon: 'none'
								});
							}
						} catch (err) {
							console.error('提交批改错误:', err);
							uni.showToast({
								title: '提交失败，请稍后重试',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		startTimer() {
			// 倒计时逻辑
			const totalSeconds = this.examInfo.duration * 60;
			let remaining = totalSeconds;
			
			const timer = setInterval(() => {
				remaining--;
				if (remaining <= 0) {
					clearInterval(timer);
					this.submitExam();
					return;
				}
				
				const hours = Math.floor(remaining / 3600);
				const minutes = Math.floor((remaining % 3600) / 60);
				const seconds = remaining % 60;
				
				this.remainingTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
			}, 1000);
		},
	}
}
</script>

<style lang="scss">
// 禁用页面滚动，只使用容器内的滚动
page {
	height: 100%;
	overflow: hidden;
}
</style>

<style lang="scss" scoped>
.exam-detail-container {
	width: 100%;
	height: 100vh;
	background: #FFF5F7;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	
	.exam-header {
		background: linear-gradient(135deg, #FFB6C1 0%, #FFC0CB 100%);
		padding: 30rpx;
		color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-shrink: 0;
		
		.btn-back {
			width: 60rpx;
			height: 60rpx;
			background: rgba(255, 255, 255, 0.3);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			padding: 0;
			flex-shrink: 0;
			
			image {
				width: 32rpx;
				height: 32rpx;
			}
		}
		
		.header-info {
			flex: 1;
			margin: 0 20rpx;
			
			.exam-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
			}
			
			.exam-meta {
				font-size: 24rpx;
				opacity: 0.9;
				
				.divider {
					margin: 0 15rpx;
				}
			}
		}
		
		.timer {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.2);
			padding: 10rpx 20rpx;
			border-radius: 30rpx;
			flex-shrink: 0;
			
			image {
				width: 28rpx;
				height: 28rpx;
				margin-right: 8rpx;
			}
			
			text {
				font-size: 26rpx;
				font-weight: bold;
			}
		}
	}
	
	.question-content {
		flex: 1;
		overflow-y: auto;
		overflow-x: hidden;
		padding: 15rpx 12rpx 140rpx 12rpx;
		box-sizing: border-box;
		
		// 加载状态
		.loading-state {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 400rpx;
			
			text {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		// 错误状态
		.error-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			min-height: 600rpx;
			padding: 40rpx 30rpx;
			text-align: center;
			
			image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
				opacity: 0.5;
			}
			
			.error-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 15rpx;
			}
			
			.error-message {
				font-size: 26rpx;
				color: #999;
				line-height: 1.6;
				margin-bottom: 40rpx;
			}
			
			.retry-btn, .back-btn {
				width: 300rpx;
				height: 70rpx;
				border-radius: 40rpx;
				border: none;
				font-size: 28rpx;
				margin-bottom: 15rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			.retry-btn {
				background: linear-gradient(135deg, #FF69B4 0%, #FFB6C1 100%);
				color: #fff;
			}
			
			.back-btn {
				background: #FFF0F5;
				color: #FFB6C1;
			}
		}
		
		// 空状态
		.empty-state {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 400rpx;
			
			text {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		.question-card {
			background: #fff;
			border-radius: 20rpx;
			padding: 20rpx 15rpx;
			margin-bottom: 20rpx;
			box-sizing: border-box;
			width: 100%;
			overflow: hidden;
			
			.question-header {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;
				
				.question-type {
					background: #FFE4E1;
					color: #FF69B4;
					padding: 8rpx 15rpx;
					border-radius: 30rpx;
					font-size: 24rpx;
					white-space: nowrap;
				}
				
				.question-score {
					color: #f44336;
					font-size: 26rpx;
					font-weight: bold;
					white-space: nowrap;
				}
			}
			
			.question-title {
				font-size: 28rpx;
				color: #333;
				line-height: 1.6;
				margin-bottom: 20rpx;
				word-wrap: break-word;
				overflow-wrap: break-word;
				width: 100%;
				box-sizing: border-box;
				overflow: hidden;
				
				.number {
					font-weight: bold;
					color: #FFB6C1;
				}
				
				// 富文本内容样式
				.html-content {
					display: block;
					word-wrap: break-word;
					overflow-wrap: break-word;
					width: 100%;
					box-sizing: border-box;
					overflow-x: hidden;
					
					img {
						max-width: 100% !important;
						width: auto !important;
						max-height: 600rpx;
						height: auto !important;
						display: block;
						margin: 15rpx auto;
						border-radius: 10rpx;
						object-fit: contain;
					}
				}
			}
			
			.options {
				.option-item {
					display: flex;
					align-items: flex-start;
					padding: 15rpx;
					margin-bottom: 12rpx;
					background: #FFF5F7;
					border-radius: 12rpx;
					transition: all 0.3s;
					box-sizing: border-box;
					width: 100%;
					
					&.selected {
						background: #FFE4E1;
						border: 2rpx solid #FFB6C1;
					}
					
					.radio, .checkbox {
						width: 32rpx;
						height: 32rpx;
						margin-right: 12rpx;
						flex-shrink: 0;
					}
					
					.option-key {
						font-weight: bold;
						margin-right: 8rpx;
						color: #666;
						flex-shrink: 0;
						min-width: 30rpx;
					}
					
					.option-text {
						flex: 1;
						font-size: 26rpx;
						color: #333;
						line-height: 1.5;
						word-wrap: break-word;
						overflow-wrap: break-word;
						word-break: break-all;
						overflow: hidden;
					}
				}
			}
			
			.judge-options {
				display: flex;
				gap: 20rpx;
				
				.judge-item {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20rpx;
					background: #FFF5F7;
					border-radius: 12rpx;
					box-sizing: border-box;
					
					&.selected {
						background: #FFE4E1;
						border: 2rpx solid #FFB6C1;
					}
					
					image {
						width: 28rpx;
						height: 28rpx;
						margin-right: 8rpx;
					}
					
					text {
						font-size: 26rpx;
						color: #333;
					}
				}
			}
			
			.answer-input {
				position: relative;
				width: 100%;
				box-sizing: border-box;
				
				textarea {
					width: 100%;
					min-height: 250rpx;
					padding: 15rpx;
					background: #FFF5F7;
					border-radius: 12rpx;
					font-size: 26rpx;
					line-height: 1.6;
					box-sizing: border-box;
					border: none;
				}
				
				.word-count {
					text-align: right;
					margin-top: 8rpx;
					font-size: 22rpx;
					color: #999;
					padding-right: 5rpx;
				}
			}
			
			.score-input {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				margin-top: 20rpx;
				padding: 15rpx 20rpx;
				background: #FFF5F7;
				border-radius: 10rpx;
				
				.score-label {
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
					margin-right: 15rpx;
					white-space: nowrap;
				}
				
				input {
					flex: 0 0 120rpx;
					height: 60rpx;
					text-align: center;
					background: #fff;
					border: 2rpx solid #FFB6C1;
					border-radius: 8rpx;
					font-size: 28rpx;
					color: #FF69B4;
					font-weight: bold;
					padding: 0 10rpx;
				}
				
				.score-total {
					font-size: 28rpx;
					color: #666;
					margin-left: 10rpx;
					white-space: nowrap;
				}
			}
		}
		
		.question-nav {
			background: #fff;
			border-radius: 15rpx;
			padding: 20rpx 15rpx;
			margin-bottom: 20rpx;
			box-sizing: border-box;
			width: 100%;
			
			.nav-title {
				font-size: 26rpx;
				font-weight: bold;
				margin-bottom: 15rpx;
				color: #333;
			}
			
			.nav-grid {
				display: grid;
				grid-template-columns: repeat(8, 1fr);
				gap: 10rpx;
				
				.nav-item {
					aspect-ratio: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					background: #FFF5F7;
					border-radius: 8rpx;
					font-size: 24rpx;
					color: #666;
					
					&.current {
						background: #FFB6C1;
						color: #fff;
					}
					
					&.answered {
						background: #FFE4E1;
						color: #FF69B4;
					}
				}
			}
		}
	}
	
	.footer-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		background: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
		z-index: 100;
		flex-shrink: 0;
		
		.btn {
			flex: 1;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50rpx;
			font-size: 28rpx;
			margin: 0 10rpx;
			border: none;
			
			&.btn-prev {
				background: #FFF0F5;
				color: #FFB6C1;
				
				&[disabled] {
					opacity: 0.5;
				}
			}
			
			&.btn-collect {
				background: #FFF0F5;
				color: #FF69B4;
				
				image {
					width: 32rpx;
					height: 32rpx;
					margin-right: 8rpx;
				}
			}
			
			&.btn-next {
				background: linear-gradient(135deg, #FFB6C1 0%, #FFC0CB 100%);
				color: #fff;
			}
			
			&.btn-submit {
				background: linear-gradient(135deg, #FF69B4 0%, #FFB6C1 100%);
				color: #fff;
			}
		}
	}
}
</style>

<style lang="scss">
// 全局样式：用于渲染 HTML 内容
.html-content {
	width: 100%;
	box-sizing: border-box;
	overflow-x: hidden;
	padding: 0 10rpx;
	
	* {
		box-sizing: border-box;
	}
	
	p {
		margin: 10rpx 0;
		line-height: 1.8;
		color: #333;
		font-size: 28rpx;
		word-wrap: break-word;
		word-break: break-all;
		overflow-x: auto;
	}
	
	img {
		max-width: 100% !important;
		width: auto !important;
		max-height: 600rpx;
		height: auto !important;
		display: block;
		margin: 15rpx auto;
		border-radius: 10rpx;
		object-fit: contain;
	}
	
	span, div {
		word-wrap: break-word;
		overflow-wrap: break-word;
		word-break: break-all;
	}
	
	table {
		width: 100% !important;
		border-collapse: collapse;
		overflow-x: auto;
		display: block;
		
		td, th {
			padding: 8rpx;
			border: 1rpx solid #ddd;
			word-break: break-all;
		}
	}
}
</style>
